﻿using System;
using MockDataTransferObject;
using MockCommon;
using MockBusiness;
using System.Web.UI.WebControls;
using System.Globalization;

namespace Presentation.AdminPresentation
{
    public partial class AddClient : System.Web.UI.Page
    {
        private RoleBusiness _roleBusiness;
        private ClientBusiness _clientBusiness;
        private UserBusiness _userBusiness;
        private Label _warningLabel;
        private Label _errorLabel;
        private Label _successLabel;
        private TextBox _firstNameTextBox;
        private TextBox _lastNameTextBox;
        private TextBox _birthdateTextBox;
        private TextBox _titleTextBox;
        private TextBox _addressTextBox;
        private TextBox _vatNumberTextBox;
        private TextBox _registerNumberTextBox;
        private TextBox _postCodeTextBox;
        private RadioButton _maleRadio;
        private DropDownList _dayInWeekDropDownList;
        private CheckBox _activeCheckBox;
        private Button _addButton;
        private Button _resetButton;

        protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
                _roleBusiness = RoleBusiness.RetrieveInstance();
                _clientBusiness = ClientBusiness.RetrieveInstance();
                _userBusiness = UserBusiness.RetrieveInstance();
                _warningLabel = (Label)Master.FindControl("WarningLabel");
                _errorLabel = (Label)Master.FindControl("ErrorLabel");
                _successLabel = (Label)Master.FindControl("SuccessLabel");
                _firstNameTextBox = (TextBox)AddClientUserControl.FindControl("FirstNameTextBox");
                _lastNameTextBox = (TextBox)AddClientUserControl.FindControl("LastNameTextBox");
                _birthdateTextBox = (TextBox)AddClientUserControl.FindControl("BirthDateTextBox");
                _titleTextBox = (TextBox)AddClientUserControl.FindControl("TitleTextBox");
                _addressTextBox = (TextBox)AddClientUserControl.FindControl("AddressTextBox");
                _vatNumberTextBox = (TextBox)AddClientUserControl.FindControl("VatNumberTextBox");
                _registerNumberTextBox = (TextBox)AddClientUserControl.FindControl("RegisterNumberTextBox");
                _postCodeTextBox = (TextBox)AddClientUserControl.FindControl("PostcodeTextBox");
                _maleRadio = (RadioButton)AddClientUserControl.FindControl("MaleRadio");
                _dayInWeekDropDownList = (DropDownList)AddClientUserControl.FindControl("DayInWeekDropDownList");
                _activeCheckBox = (CheckBox)AddClientUserControl.FindControl("ActiveCheckBox");
                _addButton = (Button)AddClientUserControl.FindControl("AddButton");
                _resetButton = (Button)AddClientUserControl.FindControl("ResetButton");
                _addButton.Click += new EventHandler(AddButton_Click);
                _resetButton.Click += new EventHandler(ResetButton_Click);
            }
            catch (MockException exception)
            {
                Application["error"] = exception;
                Response.Redirect("../Error.aspx");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["user"] != null)
            {
                User user = Session["User"] as User;
                if (user.Role.RoleName != "Admin")
                {
                    Server.Transfer("../NotAuthorized.aspx");
                }
            }
            else
            {
                Response.Redirect("../LogOn.aspx");
            }
            if (IsPostBack)
            {
                _warningLabel.Text = "";
                _errorLabel.Text = "";
                _successLabel.Text = "";
            }
        }

        protected void AddButton_Click(object sender, EventArgs e)
        {
            try
            {
                //Constant
                string clientRoleName = "Client";
                string successFormat = "Create client with user {0} successfully!";
                //Get form
                string firstName = _firstNameTextBox.Text;
                string lastName = _lastNameTextBox.Text;
                string username = _userBusiness.GenerateUserName(firstName, lastName);
                string password = UserBusiness.GeneratePassword();
                string goodFirstName = UserBusiness.FormatName(firstName);
                string goodLastName = UserBusiness.FormatName(lastName);
                string title = _titleTextBox.Text;
                string address = _addressTextBox.Text;
                string vatNumber = _vatNumberTextBox.Text;
                string registerNumber = _registerNumberTextBox.Text;
                string postCode = _postCodeTextBox.Text;
                string successText = String.Format(CultureInfo.CurrentCulture, successFormat, username);
                int dayInWeek = Convert.ToInt32(_dayInWeekDropDownList.SelectedValue, CultureInfo.CurrentCulture);
                object roleId = _roleBusiness.GetRoleIdByRoleName(clientRoleName);
                bool isActive = _activeCheckBox.Checked;
                bool gender = _maleRadio.Checked ? true : false;
                DateTime birthdate = Convert.ToDateTime(_birthdateTextBox.Text, CultureInfo.CurrentCulture);
                Guid userId = Guid.NewGuid();
                Guid clientId = Guid.NewGuid();
                //Create role
                Role role = new Role();
                role.RoleId = (Guid)roleId;
                //Create user
                User user = new User();
                user.UserId = userId;
                user.Role = role;
                user.UserName = username;
                user.Password = password;
                user.IsActive = isActive;
                //Create client
                Client client = new Client();
                client.ClientId = clientId;
                client.FirstName = goodFirstName;
                client.LastName = goodLastName;
                client.BirthDate = birthdate;
                client.Gender = gender;   
                client.User = user;
                client.Title = title;
                client.Address = address;
                client.VatNumber = vatNumber;
                client.RegisterNumber = registerNumber;
                client.Postcode = postCode;
                client.DayInWeek = dayInWeek;
                //Create
                _clientBusiness.Insert(client);
                _successLabel.Text = successText;
                //Finally reset
                Reset();
            }
            catch (NullReferenceException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (ArgumentException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (FormatException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        protected void ResetButton_Click(object sender, EventArgs e)
        {
            Reset();
        }

        protected void Reset()
        {
            _firstNameTextBox.Text = "";
            _lastNameTextBox.Text = "";
            _birthdateTextBox.Text = "";
            _maleRadio.Checked = true;
            _titleTextBox.Text = "";
            _addressTextBox.Text = "";
            _vatNumberTextBox.Text = "";
            _registerNumberTextBox.Text = "";
            _postCodeTextBox.Text = "";
            _dayInWeekDropDownList.ClearSelection();
            _activeCheckBox.Checked = true;
        }
    }
}